﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web;
using System.Threading;
using ThinggoWorlducUtils;

namespace WorlducClient
{
    public partial class FrmMain : Form
    {
        private WorlducUtils utils = new WorlducUtils();
        //当前的组ID
        private String curGroupId = "";
        
        private Random rdm = new Random();
        private CookieContainer cookieContainer = new CookieContainer();            
        private string myuid = "";        
        private const string FILE_FRIEND_LIST = "friends.txt";
        private const string STUDENTS_JOB_FILE = "students.xlsx";
        //好友数据
        private List< WorlducUtils.Person> personList = new List<WorlducUtils.Person>();
        //好友分组
        private List<WorlducUtils.FriendGroup> groupList = new List<WorlducUtils.FriendGroup>();

        //博文列表
        private List<WorlducUtils.BlogArticle> articleList = new List<WorlducUtils.BlogArticle>();

        //未回复的留言列表
        private List<WorlducUtils.LeaveWord> unReplyList = new List<WorlducUtils.LeaveWord>();
        
        private delegate void MyButtonDelegate(Button btn);

        private List<WorlducUtils.Person> studentList = new List<WorlducUtils.Person>();
        //一个月试用期
        private bool IsTryUse()
        {
            try
            {
                string path = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;
                int x = path.LastIndexOf(":///");
                path = path.Substring(x + 4);
                FileInfo fi = new FileInfo(path);
                TimeSpan ts = DateTime.Now - fi.CreationTime;
                return Math.Abs(ts.TotalDays) < 360;
            }
            catch { return false; }
        }

        private WorlducUtils.FriendGroup getGroupByGroupId(String gid)
        {
            foreach (WorlducUtils.FriendGroup g in groupList)
            {
                if (g.GroupId == gid) return g;
            }
            return null;
        }
        public FrmMain()
        {
            InitializeComponent();

            if (!IsTryUse())
            {
                Application.Exit();
            }

            txtHint.Text = "这里是消息区，双击清空消息";
            cbWeiBoMood.SelectedIndex = 0;

            //导入链接文件
            personList.Clear();
            string fileName = FILE_FRIEND_LIST;
            StreamReader sr = null;
            
            if (File.Exists(fileName))
            {
                //读取本地的好友信息
                sr = new StreamReader(fileName, Encoding.UTF8);
                string line = sr.ReadLine();                
                while (line != null && line.Length > 5)
                {
                    try
                    {
                        int x = line.IndexOf("|");
                        if (x >= 0)
                        {
                            string groupId = line.Substring(0, x);
                            line = line.Substring(x + 1);
                            x = line.IndexOf("|");
                            //所属组名
                            string groupName = line.Substring(0, x);
                            line = line.Substring(x + 1);
                            x = line.IndexOf("|");
                            //好友姓名
                            string name = line.Substring(0, x).Trim();
                            //好友编号
                            string uid = line.Substring(x + 1).Trim();
                            WorlducUtils.FriendGroup fg = new WorlducUtils.FriendGroup(groupName, 1, groupId);
                            WorlducUtils.Person p = new WorlducUtils.Person(name, uid, groupName);
                            p.Group = fg;
                            personList.Add(p);
                            WorlducUtils.FriendGroup g = getGroupByGroupId(groupId);
                            if (g != null)
                            {
                                g.Count++;
                            }
                            else
                            {
                                groupList.Add(fg);
                            }

                        }
                    }
                    catch (Exception ex) { }
                    line = sr.ReadLine();
                }
                sr.Close();
            }
            //分组
            cbGroup.Items.Clear();
            cbGroup.Items.Add(new WorlducUtils.FriendGroup("所有分组", personList.Count, "-1"));
            cbGroup.SelectedIndex = 0;
            foreach (WorlducUtils.FriendGroup fg in groupList)
            {
                cbGroup.Items.Add(fg);
            }
            //填充好友下拉框
            cbUser.Items.Clear();
            foreach (WorlducUtils.Person p in personList)
            {
                cbUser.Items.Add(p);
            }
                        
            //读取用户名和密码信息
            try
            {
                sr = null;
                sr = new StreamReader(new FileStream("user.dat", FileMode.OpenOrCreate, FileAccess.Read));
                string userName = sr.ReadLine();
                int x = userName.IndexOf("=");
                userName = userName.Substring(x + 1);
                string pwd = sr.ReadLine();
                x = pwd.IndexOf("=");
                pwd = pwd.Substring(x + 1);
                txtUserName.Text = userName;
                txtPassword.Text = pwd;
                sr.Close();
            }
            catch {
                if (sr != null) sr.Close();
            }

            //广告线程
            Thread th = new Thread(new ThreadStart(Nav_Adv));
            th.Start();
        }

        //显示数据
        private void SetText(string s)
        {
            txtHint.AppendText(s + Environment.NewLine);
            //txtHint.Text = s + Environment.NewLine + txtHint.Text;
        }

        //显示数据
        private void SetText2(string url)
        {
             txtBlogArticleUrl.Text = url;
        }

        private void EnableButton(Button btn) {
            btn.Enabled = true;
        }
        private void Nav_Adv() {
            string html = utils.HttpGet(WorlducCfg.ADV_URL);
            HtmlAgilityPack.HtmlDocument hd = new HtmlAgilityPack.HtmlDocument();
            hd.LoadHtml(html);
            string url = hd.GetElementbyId("wumingxingurl").InnerText;
            //MyDelegate md = new MyDelegate(SetText);   
            //Invoke(md,utils.HttpGet(url));   
        }
        private void cbGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbUser.Items.Clear();
            if (cbGroup.SelectedIndex == 0)
            {
                foreach (WorlducUtils.Person p in personList)
                {
                    cbUser.Items.Add(p);
                }
            }
            else
            {
                WorlducUtils.FriendGroup g = (WorlducUtils.FriendGroup)cbGroup.SelectedItem;
                foreach (WorlducUtils.Person p in personList)
                {
                    if (p.Group.GroupId != g.GroupId) continue;
                    cbUser.Items.Add(p);
                }
            }
        }
        //登录大学城
        private void btnLogin_Click(object sender, EventArgs e)
        {
            btnLogin.Enabled = false;
            string userName =txtUserName.Text;//用户名
            string password = txtPassword.Text;//密码
            myuid = utils.Login(userName, password);
            lblUid.Text = myuid;
            if (myuid != string.Empty)
            {
                txtHint.Text = "登录成功！";
                StreamWriter sw = new StreamWriter(new FileStream("user.dat", FileMode.Create, FileAccess.Write));
                sw.WriteLine("userName={0}", userName);
                sw.WriteLine("password={0}", password);
                sw.Close();
            }
            else {
                txtHint.Text = "登录失败！";
            }
            
            btnLogin.Enabled = true;
            //广告线程
            Thread th = new Thread(new ThreadStart(Nav_Adv));
            th.Start();
        }

        private void btnWeiBo_Click(object sender, EventArgs e)
        {
            if (!utils.IsLogined())
            {
                MessageBox.Show("请先登录!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (txtWeiBoContent.Text.Trim() == "")
            {
                MessageBox.Show("请输入微博内容!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            btnWeiBo.Enabled = false;
            bool bOK = utils.IssueWeiBo(txtWeiBoContent.Text);
            if (!bOK)
            {
                txtHint.Text = "微博发布失败！";
            }
            else
            {
                txtHint.Text = "微博发布成功！";
            }
            btnWeiBo.Enabled = true;
        }

        private void btnLeaveMessage_Click(object sender, EventArgs e)
        {
            if (!utils.IsLogined()) {
                MessageBox.Show("请先登录!","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }
            if (txtMessage.Text.Trim() == "")
            {
                MessageBox.Show("请输入留言内容!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            btnLeaveMessage.Enabled = false;
            txtHint.Text = "正在留言...";
            if (cbUser.SelectedItem == null && cbUser.Items.Count > 0)
            {
                Thread th = new Thread(new ThreadStart(LeaveMessageForAll));
                th.Start();
            }
            else if (cbUser.SelectedItem != null)
            {

                WorlducUtils.Person p = (WorlducUtils.Person)cbUser.SelectedItem;
                txtHint.Text = "正在给" + p + "留言...";
                bool bOK = utils.IssueLeaveword(txtMessage.Text, p.Uid);
                if (!bOK)
                {
                    txtHint.Text += "   留言失败！";
                }
                else {
                    txtHint.Text += "   留言成功！";
                }
                btnLeaveMessage.Enabled = true;
            }
            else
            {
                string uid = 100 + rdm.Next(1000000) + "";
                MessageBox.Show("系统将随机找一位用户进行留言\r\n留言的用户是:" + uid);
                txtHint.Text = "正在给" + uid + "留言...";
                bool bOK = utils.IssueLeaveword(txtMessage.Text, uid);
                if (!bOK)
                {
                    txtHint.Text += "    留言失败！";
                }
                else
                {
                    txtHint.Text += "   留言成功！";
                }
                btnLeaveMessage.Enabled = true;
            }  
            
        }


        private void LeaveMessageForAll()
        {
            MyDelegate md = new MyDelegate(SetText);
            
            foreach (WorlducUtils.Person p in cbUser.Items)
            {
                Invoke(md, "正在给" + p + "留言...");
                bool bOK = utils.IssueLeaveword(txtMessage.Text, p.Uid);
                if (!bOK)
                {
                    Invoke(md, "给" + p + "留言失败！");
                }
                else
                {
                    Invoke(md, "给" + p + "留言成功！");
                }
            }
            MyButtonDelegate mdb = new MyButtonDelegate(EnableButton);
            Invoke(mdb, btnLeaveMessage);
        }


        private void afterGetFriendList(string msg) {
            cbGroup.Items.Clear();
            cbGroup.Items.Add(new WorlducUtils.FriendGroup("所有分组", personList.Count, "-1"));
            foreach (WorlducUtils.FriendGroup fg in groupList)
            {
                cbGroup.Items.Add(fg);
            }
            //填充好友列表
            cbUser.Items.Clear();
            foreach (WorlducUtils.Person p in personList)
            {
                cbUser.Items.Add(p);
            }
            if (cbUser.Items.Count > 0)
            {
                cbUser.Items.Insert(0, "所有人("+personList.Count+")");
                cbUser.SelectedIndex = 0;
            }
            txtHint.Text = "好友数:" + personList.Count;
            btnFriendList.Enabled = true;
        }

        
        private void GetFriendListThread() {

            groupList.Clear();
            personList.Clear();
            MyDelegate showmsg = new MyDelegate(SetText);
            groupList.AddRange(utils.GetFriendGroupList());
            Invoke(showmsg, "共获取【" + groupList.Count + "】个分组!");
            
            List<WorlducUtils.Person> persons = new List<WorlducUtils.Person>();
            foreach (WorlducUtils.FriendGroup group in groupList)
            {
                persons.Clear();
                Invoke(showmsg, "【" + group.GroupName + "】分组有【"+group.Count+"】个好友,开始获取...");                
                for (int i = 1; i <= group.Pages; i++)  //循环处理每1分页的好友列表
                {
                    Invoke(showmsg, " "+i);
                    List<WorlducUtils.Person> list = utils.GetFriendListByPage(group, i);
                    persons.AddRange(list);                    
                }
                personList.AddRange(persons);
                Invoke(showmsg, "【" + group.GroupName + "】分组共获得【"+persons.Count+"】个好友!");                
            }            
            //保存好友            
            StreamWriter sw = new StreamWriter(new FileStream(FILE_FRIEND_LIST, FileMode.Create, FileAccess.Write));
            foreach (WorlducUtils.Person person in personList)
            {
                sw.WriteLine(person.ToString());
            }
            sw.Flush();
            sw.Close();
            //更新界面
            MyDelegate md = new MyDelegate(afterGetFriendList);            
            Invoke(md, "");
        }
       
        private void btnFriendList_Click(object sender, EventArgs e)
        {
            if (!utils.IsLogined())
            {
                MessageBox.Show("请先登录!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            btnFriendList.Enabled = false;
            txtHint.Text = "正在获取好友列表..."+Environment.NewLine;
            //启动线程获取好友列表
            Thread th = new Thread(new ThreadStart(GetFriendListThread));
            th.Start();
        }
        
        private void btnAutoReply_Click(object sender, EventArgs e)
        {            
            if (!utils.IsLogined())
            {
                MessageBox.Show("请先登录!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            btnAutoReply.Enabled = false;
            txtHint.Text = "正在回复留言...";
            Thread th = new Thread(new ThreadStart(AutoReplyAllWord));
            th.Start();
        }
        
        private void AutoReplyAllWord() {
            MyDelegate md = new MyDelegate(SetText);
            MyButtonDelegate mdb = new MyButtonDelegate(EnableButton);
            string replyText = txtMessage.Text.Trim();
            bool bRandom = txtMessage.Text.Trim().Length == 0;
            int totals = 0;
            foreach (WorlducUtils.LeaveWord word in unReplyList) { 
                if (bRandom && listAutoReplyText.Items.Count > 0)
                {
                    int idx = Convert.ToInt32(word.WordID) % listAutoReplyText.Items.Count;
                    replyText = listAutoReplyText.Items[idx].ToString();
                }
                Invoke(md, "正在回复【" + word.WordID + "】留言!【"+replyText+"】");   
                int count = utils.AutoReplyWord(word.WordID, replyText);
                if (count > 0)
                {
                    totals++;
                    Invoke(md, "回复【" + word.WordID + "】留言成功!");
                }
                else {
                    Invoke(md, "回复【" + word.WordID + "】留言失败!");
                }  
            }
            Invoke(md, "自动回复了" + totals + "条留言!");
            Invoke(mdb, btnAutoReply);
        }

        private void UnReplyCount() {
            MyDelegate md = new MyDelegate(SetText);
            MyButtonDelegate mdb = new MyButtonDelegate(EnableButton);
            unReplyList.Clear();
            unReplyList = utils.GetUnReplyWordList();
            foreach (WorlducUtils.LeaveWord lw in unReplyList) {
                Invoke(md, lw.ToString());
            }
            Invoke(md,"有" + unReplyList.Count + "条留言未回复!");
            Invoke(mdb, btnUnReplyCount);
        }
        
        private void btnUnReplyCount_Click(object sender, EventArgs e)
        {
            if (!utils.IsLogined())
            {
                MessageBox.Show("请先登录!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            btnUnReplyCount.Enabled = false;
            txtHint.Text = "正在获取未回复的留言信息...";
            Thread th = new Thread(new ThreadStart(UnReplyCount));
            th.Start();
        }


        private void GetBlogArticleList() {
            string url = txtBlogArticleUrl.Text;
            int x = url.IndexOf("sid=");
            int y = url.IndexOf("uid=");            
            string sid = url.Substring(x + 4);
            x = sid.IndexOf("&");
            if (x > 0)
            {
                sid = sid.Substring(0, x);
            }
            string uid = url.Substring(y + 4);
            y = uid.IndexOf("&");
            if (y > 0)
            {
                uid = uid.Substring(0, y);
            }

            articleList.Clear();
            MyDelegate md = new MyDelegate(SetText);
            MyButtonDelegate mdb = new MyButtonDelegate(EnableButton);

            List<WorlducUtils.BlogArticleCategory> categoyList = utils.GetBlogArticleListBySId(sid, uid);
            foreach (WorlducUtils.BlogArticleCategory c in categoyList)
            {
                Invoke(md, c.ToString() + Environment.NewLine + "=====================" + Environment.NewLine);                
                List<WorlducUtils.BlogArticle> aList = utils.GetBlogArticleListBySIdCId(c);
                articleList.AddRange(aList);
                foreach (WorlducUtils.BlogArticle b in aList)
                {                    
                    Invoke(md, b.ToString() + Environment.NewLine);                                
                }
            }
            Invoke(md, "共有"+articleList.Count+"篇博文!" + Environment.NewLine);    
            Invoke(mdb, btnBlogArticleList);        
        }

        private void btnBlogArticleList_Click(object sender, EventArgs e)
        {            
            string url = txtBlogArticleUrl.Text;
            int x = url.IndexOf("sid=");
            int y = url.IndexOf("uid=");
            if(x<0 || y<0){
                MessageBox.Show("你输入的二级栏目地址不正确\r\n格式为：http://www.worlduc.com/SpaceShow/Blog/List.aspx?sid=4636173&uid=134940",
                    "错误",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                return;
            }
            btnBlogArticleList.Enabled = false;
            
            txtHint.Text = "";
            Thread th = new Thread(new ThreadStart(GetBlogArticleList));
            th.Start();
            
        }


        private void AutoReplyBlogArticleList() {
            string replyText = txtMessage.Text.Trim();
            bool bRandom = txtMessage.Text.Trim().Length == 0;
            MyDelegate md = new MyDelegate(SetText);
            MyButtonDelegate mdb = new MyButtonDelegate(EnableButton);

            int totals = 0;
            foreach (WorlducUtils.BlogArticle ba in articleList)
            {
                if (ba.ReplyCount == 0 || chkReplyAllArticle.Checked)
                {
                    if (bRandom && listAutoReplyText.Items.Count > 0)
                    {
                        int idx = Convert.ToInt32(ba.WordID) % listAutoReplyText.Items.Count;
                        replyText = listAutoReplyText.Items[idx].ToString();
                    }
                    Thread.Sleep(5000);                   
                    int count = utils.ReplyBlogArticleByBlogId(ba.WordID, replyText);
                    ba.ReplyCount = count;
                    if (count > 0)
                    {
                        totals++;
                        Invoke(md, ba.WordID + "[" + replyText + "]" + Environment.NewLine);
                    }
                }
            }
            Invoke(md, "共回复了" + totals + "篇博文" + Environment.NewLine);
            Invoke(mdb, btnBatchReplyComent);   
        }

        private void btnBatchReplyComent_Click(object sender, EventArgs e)
        {
            if (!utils.IsLogined())
            {
                MessageBox.Show("请先登录!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            btnBatchReplyComent.Enabled = false;
            txtHint.Text = "";
            Thread th = new Thread(new ThreadStart(AutoReplyBlogArticleList));
            th.Start();
            
        }

        List<String> logfiles = new List<string>();
        private void btnReplyByFile_Click(object sender, EventArgs e)
        {
            if (!utils.IsLogined())
            {
                MessageBox.Show("请先登录!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
            OpenFileDialog dlg = new OpenFileDialog();
            if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK) return;
            StreamReader sr = new StreamReader(dlg.FileName);
            string line = sr.ReadLine();
            txtHint.Text = "";
            logfiles.Clear();
            while (line != null) {
                try
                {
                    string url = line.Trim();
                    int x = url.IndexOf("sid=");
                    int y = url.IndexOf("uid=");
                    if (x < 0 || y < 0)
                    {
                        txtHint.Text += Environment.NewLine + url + "格式不正确";
                    }
                    else
                    {
                        logfiles.Add(url.Trim());
                    }
                }
                catch { 

                }
                line = sr.ReadLine();
            }
            if (logfiles.Count <= 0)
            {
                txtHint.Text += Environment.NewLine + "没有合法的连接！";  
                return;
            }
            txtHint.Text += Environment.NewLine + " 文件读取完毕，开始进行回复...";
            
            btnReplyByFile.Enabled = false;
            Thread th = new Thread(new ThreadStart(relpyByFiles));
            th.Start();              
        }

        private void relpyByFiles() {
            MyDelegate md = new MyDelegate(SetText);
            MyDelegate mdd = new MyDelegate(SetText2);
            MyButtonDelegate mdb = new MyButtonDelegate(EnableButton);
            int totals = 0;
            foreach (string url in logfiles) {
                int x = url.IndexOf("sid=");
                int y = url.IndexOf("uid=");
                string sid = url.Substring(x + 4);
                x = sid.IndexOf("&");
                if (x > 0)
                {
                    sid = sid.Substring(0, x);
                }
                string uid = url.Substring(y + 4);
                y = uid.IndexOf("&");
                if (y > 0)
                {
                    uid = uid.Substring(0, y);
                }

                articleList.Clear();
                Invoke(mdd, url);
                txtHint.Text = "";                
                

                List<WorlducUtils.BlogArticleCategory> categoyList = utils.GetBlogArticleListBySId(sid, uid);
                foreach (WorlducUtils.BlogArticleCategory c in categoyList)
                {
                    Invoke(md, c.ToString() + Environment.NewLine + "=====================" + Environment.NewLine);
                    List<WorlducUtils.BlogArticle> aList = utils.GetBlogArticleListBySIdCId(c);
                    articleList.AddRange(aList);
                    foreach (WorlducUtils.BlogArticle b in aList)
                    {
                        Invoke(md, b.ToString() + Environment.NewLine);
                    }
                }
                Invoke(md, "共有" + articleList.Count + "篇博文!" + Environment.NewLine);
                
                string replyText = txtMessage.Text.Trim();
                bool bRandom = txtMessage.Text.Trim().Length == 0;                

                
                foreach (WorlducUtils.BlogArticle ba in articleList)
                {
                    if (ba.ReplyCount == 0 || chkReplyAllArticle.Checked)
                    {
                        if (bRandom && listAutoReplyText.Items.Count > 0)
                        {
                            int idx = Convert.ToInt32(ba.WordID) % listAutoReplyText.Items.Count;
                            replyText = listAutoReplyText.Items[idx].ToString();
                        }
                        int count = utils.ReplyBlogArticleByBlogId(ba.WordID, replyText);
                        Thread.Sleep(3000);
                        ba.ReplyCount = count;
                        if (count > 0)
                        {
                            totals++;
                            Invoke(md, ba.WordID + "[" + replyText + "]" + Environment.NewLine);
                        }
                    }
                }
                           
            }
            Invoke(md, "共回复了" + totals + "篇博文" + Environment.NewLine);     
            Invoke(mdb, btnReplyByFile);                
        }


        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (txtAutoText.Text.Trim().Length > 0)
            {
                listAutoReplyText.Items.Add(txtAutoText.Text);
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (listAutoReplyText.SelectedIndex >= 0) {
                listAutoReplyText.Items.RemoveAt(listAutoReplyText.SelectedIndex);
            }
        }

        private void VisitFirends() {
            MyDelegate md = new MyDelegate(SetText);
            MyButtonDelegate mdb = new MyButtonDelegate(EnableButton);
            foreach (WorlducUtils.Person p in cbUser.Items) {
                Invoke(md,"正在访问["+p.Name + "] "+p.HomeUrl);
                utils.HttpGet(p.HomeUrl);
            }
            Invoke(mdb, btnVisitFriends);
        }

        //访问cbUser中的所有好友
        private void btnVisitFriends_Click(object sender, EventArgs e)
        {
            txtHint.Text = "";
            if (!utils.IsLogined())
            {
                MessageBox.Show("请先登录!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            btnVisitFriends.Enabled = false;
            Thread th = new Thread(new ThreadStart(VisitFirends));
            th.Start();
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }


        private void btnArticle_Click(object sender, EventArgs e)
        {
            if (!utils.IsLogined())
            {
                MessageBox.Show("请先登录!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            FrmIssueArticle frm = new FrmIssueArticle();
            frm.utils = utils;
            frm.ShowDialog(this);
        }

        private void ArticleSingleCount()
        {
            if (!utils.IsLogined())
            {
                MessageBox.Show("请先登录!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            int p = txtBlogUrl.Text.IndexOf("bid=");
            if (p <= 0)
            {
                MessageBox.Show("要统计的地址不合法!格式如下：\nhttp://worlduc.com/blog2012.aspx?bid=22657162", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);              
                return;
            }
           
            string bid = txtBlogUrl.Text.Substring(p + 4);
            int x = bid.IndexOf("&");
            if (x > 0) {
                bid = bid.Substring(0, x);
            }

            string content = utils.getReplyContentById(bid);
            
            List<WorlducUtils.Comment> list = utils.getCommentsByBlogId(bid);

            genShowHtmlFile(list, bid, "B");
                      
        }

        private void genShowHtmlFile(List<WorlducUtils.Comment> list, string bid, string flag)
        {
            list.Sort();
            int rowNo = 1;
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<html><head><base='http://www.worlduc.com/'/><title>评论统计</title></head><body><table width='100%'>");
            sb.AppendFormat("<tr><td style='width:100px'>{0}</td><td style='width:100px'>{1}</td><td style='width:100px'>{2}</td><td style='width:150px'>{3}</td><td style='width:500px'><div style='display:none'>{4}</div></td></tr>",
                    "序号", "用户编号", "用户姓名", "评论时间", "评论内容");
            for (int k = 0; k < list.Count; k++)
            {
                WorlducUtils.Comment c = list[k];
                if (GetPerson(studentList, c.Author.Uid) == null) continue;
                sb.AppendFormat("<tr><td style='width:100px'>{0}</td><td style='width:100px'>{1}</td><td style='width:100px'>{2}</td><td style='width:150px'>{3}</td><td style='width:500px'><div style='display:none'>{4}</div></td></tr>",
                    rowNo++, c.Author.Uid, c.Author.Name, c.Time, "");
                //setChecked(c.Author);
                setChecked(c);
                sb.AppendLine();
            }
            //saveExcel();
            string uncommenter = getUnCommenter();
            sb.AppendFormat("<tr><td colspan='5' style='width:500px'>{0}</td></tr>", uncommenter);

            sb.AppendLine("</table></body></html>");
            if (!Directory.Exists("tmp"))
            {
                Directory.CreateDirectory("tmp");
            }
            string fileName = "tmp/" + flag.ToUpper() + bid + ".html";
            StreamWriter sw = new StreamWriter(fileName, false, Encoding.UTF8);
            sw.WriteLine(sb.ToString());
            sw.Close();

            FileInfo fi = new FileInfo(fileName);
            FrmViewDoc f = new FrmViewDoc(fi.FullName);
            f.ShowDialog();   
        }

        private void genShowHtmlFile(List<WorlducUtils.LeaveWord> list)
        {
            list.Sort();
            int rowNo = 1;
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<html><head><base='http://www.worlduc.com/'/><title>留言统计</title></head><body><table width='100%'>");
            sb.AppendFormat("<tr><td style='width:100px'>{0}</td><td style='width:100px'>{1}</td><td style='width:100px'>{2}</td><td style='width:150px'>{3}</td><td style='width:500px'><div style='display:none'>{4}</div></td></tr>",
                    "序号", "留言编号", "用户姓名", "留言时间", "留言内容");
            for (int k = 0; k < list.Count; k++)
            {
                WorlducUtils.LeaveWord c = list[k];
                if (GetPerson(studentList, c.Who) == null) continue;
                sb.AppendFormat("<tr><td style='width:100px'>{0}</td><td style='width:100px'>{1}</td><td style='width:100px'>{2}</td><td style='width:150px'>{3}</td><td style='width:500px'><div style='display:block'>{4}</div></td></tr>",
                    rowNo++, c.Sender.Uid, c.Sender.Name, c.LeaveTime, c.WordText);
                setChecked(c.Sender);
                sb.AppendLine();
            }
            string uncommenter = getUnCommenter();
            sb.AppendFormat("<tr><td colspan='5' style='width:500px'>{0}</td></tr>", uncommenter);

            sb.AppendLine("</table></body></html>");
            if (!Directory.Exists("tmp"))
            {
                Directory.CreateDirectory("tmp");
            }
            string fileName = "tmp/Letter" + string.Format("{0:yyyyMMdd}",DateTime.Now)+ ".html";
            StreamWriter sw = new StreamWriter(fileName, false, Encoding.UTF8);
            sw.WriteLine(sb.ToString());
            sw.Close();

            FileInfo fi = new FileInfo(fileName);
            FrmViewDoc f = new FrmViewDoc(fi.FullName);
            f.ShowDialog();

        }
        private void genShowHtmlFile(List<WorlducUtils.PrivateLetter> list)
        {
            list.Sort();
            int rowNo = 1;
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<html><head><base='http://www.worlduc.com/'/><title>私信统计</title></head><body><table width='100%'>");
            sb.AppendFormat("<tr><td style='width:100px'>{0}</td><td style='width:100px'>{1}</td><td style='width:100px'>{2}</td><td style='width:150px'>{3}</td><td style='width:500px'><div style='display:none'>{4}</div></td></tr>",
                    "序号", "发信编号", "用户姓名", "评论时间", "评论内容");
            for (int k = 0; k < list.Count; k++)
            {
                WorlducUtils.PrivateLetter c = list[k];
                if (GetPerson(studentList, c.Sender.Uid) == null) continue;
                sb.AppendFormat("<tr><td style='width:100px'>{0}</td><td style='width:100px'>{1}</td><td style='width:100px'>{2}</td><td style='width:150px'>{3}</td><td style='width:500px'><div style='display:block'>{4}</div></td></tr>",
                    rowNo++, c.Sender.Uid, c.Sender.Name, c.RecvTime, c.Title);
                setChecked(c.Sender);
                sb.AppendLine();
            }
            string uncommenter = getUnCommenter();
            sb.AppendFormat("<tr><td colspan='5' style='width:500px'>{0}</td></tr>", uncommenter);

            sb.AppendLine("</table></body></html>");
            if (!Directory.Exists("tmp"))
            {
                Directory.CreateDirectory("tmp");
            }
            string fileName = "tmp/Letter" + string.Format("{0:yyyyMMdd}",DateTime.Now)+ ".html";
            StreamWriter sw = new StreamWriter(fileName, false, Encoding.UTF8);
            sw.WriteLine(sb.ToString());
            sw.Close();

            FileInfo fi = new FileInfo(fileName);
            FrmViewDoc f = new FrmViewDoc(fi.FullName);
            f.ShowDialog();

        }

        private void BatchArticleListCount()
        {
            
            string url = txtBlogUrl.Text;
            int x = url.IndexOf("sid=");
            int y = url.IndexOf("uid=");
            int z = url.IndexOf("cid=");
            if (x < 0 || y < 0) {
                MessageBox.Show("要统计的地址不合法!格式如下：\nhttp://worlduc.com/SpaceShow/Blog/List.aspx?sid=7047115&uid=134940", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string cid = "";
            if (z > 0) {
                cid = url.Substring(z + 4);
                z = cid.IndexOf("&");
                cid = cid.Substring(0, z);
            }
            string sid = url.Substring(x + 4);
            x = sid.IndexOf("&");
            if (x > 0)
            {
                sid = sid.Substring(0, x);
            }
            string uid = url.Substring(y + 4);
            y = uid.IndexOf("&");
            if (y > 0)
            {
                uid = uid.Substring(0, y);
            }

            articleList.Clear();
            
            //获取自定义栏目
            List<WorlducUtils.BlogArticleCategory> categoyList = utils.GetBlogArticleListBySId(sid, uid);
            foreach (WorlducUtils.BlogArticleCategory c in categoyList)
            {
                if (cid != "" && cid != c.CId) continue;
                List<WorlducUtils.BlogArticle> aList = utils.GetBlogArticleListBySIdCId(c);
                if (aList.Count > 0) 
                    articleList.AddRange(aList);               
            }

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<html><head><base='http://www.worlduc.com'/><title>栏目内容评价统计</title></head><body><table width='100%'>");

            Dictionary<String, UserScore> ht = new Dictionary<string, UserScore>();
            List<WorlducUtils.Comment> list = new List<WorlducUtils.Comment>();
            foreach (WorlducUtils.BlogArticle b in articleList)
            {
                sb.AppendFormat("<tr><td colspan='5' style='width:100%'><hr/>[{0}]{1}<hr/></td></tr>",
                           b.WordID,b.Title);
                        
                string bid = b.WordID;
                Thread.Sleep(100);
                    
                //string content = utils.getReplyContentById(bid);
                //Thread.Sleep(100);

                list = utils.getCommentsByBlogId(bid);
                list.Sort();
                int rowNo = 1;
                // 10-k/5
                sb.AppendFormat("<tr><td style='width:100px'>{0}</td><td style='width:100px'>{1}</td><td style='width:100px'>{2}</td><td style='width:150px'>{3}</td><td style='width:500px'><div style='display:none'>{4}</div></td></tr>",
                       "序号", "空间编号", "姓名", "评论时间", "评论内容");
                for (int k = 0; k < list.Count; k++)
                {
                    WorlducUtils.Comment c = list[k];
                    if (GetPerson(studentList, c.Author.Uid) == null) continue;
                    sb.AppendFormat("<tr><td style='width:100px'>{0}</td><td style='width:100px'>{1}</td><td style='width:100px'>{2}</td><td style='width:150px'>{3}</td><td style='width:500px'><div style='display:none'>{4}</div></td></tr>",
                        rowNo++, c.Author.Uid, c.Author.Name, c.MyTime, c.Content);
                    setChecked(c.Author);
                    sb.AppendLine();
                    if (ht.ContainsKey(c.Author.Name))
                    {
                        ht[c.Author.Name].Score += (10 - k / 5);
                        ht[c.Author.Name].Count++;
                    }
                    else
                    {
                        ht.Add(c.Author.Name, new UserScore(1,10 - k / 5));
                    }
                }
            }
            int line = 1;
            sb.AppendFormat("<tr><td colspan='5' style='width:500px'>共{0}篇文章，汇总统计结果如下：</td></tr>", articleList.Count);
            

            sb.AppendFormat("<tr><td style='width:100px'>{0}</td><td colspan='2' style='width:200px'>{1}</td><td style='width:100px'>{2}</td><td style='width:100px'>{3}</td></tr>",
                        "序号", "标题", "评论次数", "评论成绩");
            foreach (KeyValuePair<string, UserScore> kv in ht)
            {
                sb.AppendFormat("<tr><td style='width:100px'>{0}</td><td colspan='2' style='width:200px'>{1}</td><td style='width:100px'>{2}</td><td style='width:100px'>{3}</td></tr>",
                        line++, kv.Key, kv.Value.Count, kv.Value.Score);
            }

            string uncommenter = getUnCommenter();
            sb.AppendFormat("<tr><td colspan='5' style='width:500px'>{0}</td></tr>", uncommenter);

            sb.AppendLine("</table></body></html>");            
           
            if (!Directory.Exists("tmp"))
            {
                Directory.CreateDirectory("tmp");
            }
            string fileName = "S"+ sid + ".html";
            StreamWriter sw = new StreamWriter("tmp/" + fileName, false, Encoding.UTF8);
            sw.WriteLine(sb.ToString());
            sw.Close();

            FileInfo fi = new FileInfo("tmp/" + fileName);
            FrmViewDoc f = new FrmViewDoc(fi.FullName);
            f.ShowDialog();          
        }

        private void TopicSingleCount()
        {
            //http://group.worlduc.com/GroupShow/Topic.aspx?tid=4893247
            string url = txtBlogUrl.Text;
            int y = url.IndexOf("Topic.aspx");
            int x = url.IndexOf("tid=");
            if (y < 0 || x < y)
            {
                MessageBox.Show("要统计的地址不合法!格式如下：\nhttp://group.worlduc.com/GroupShow/Topic.aspx?tid=4893247", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            url = url.Substring(x + 4);
            x = url.IndexOf('&');
            string tid = "";
            if (x > 0)
                tid = url.Substring(0, x);
            else
                tid = url;
            
            if (tid != "")
            {
                List<WorlducUtils.Comment> comments = utils.GetCommentByTopicId(tid);
                foreach (WorlducUtils.Comment t in comments)
                {
                    txtHint.AppendText(t.Author + Environment.NewLine);
                }
                genShowHtmlFile(comments, tid, "T");

            }
        }

        /// <summary>
        /// 统计群组主题列表评论
        /// </summary>
        private void TopicListCount()
        {
            //http://group.worlduc.com/GroupShow/TopicList.aspx?gid=39575&tclass=12584&...
            string url = txtBlogUrl.Text;
            int x = url.IndexOf("TopicList.aspx");
            int y = url.IndexOf("gid=");
            if (x < 0 || y < x)
            {
                MessageBox.Show("要统计的地址不合法!格式如下：\nhttp://group.worlduc.com/GroupShow/TopicList.aspx?gid=39575&....", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string tmp = url.Substring(y+4);
            int tt = tmp.IndexOf("&");
            if (tt < 0) tt = tmp.Length;
            string gid = tmp.Substring(0, tt);

            int z = url.IndexOf("tclass=");
            string tclass = "0";
            if (z >= 0)
            {
                tmp = url.Substring(z + 7);
                tt = tmp.IndexOf("&");
                if (tt < 0) tt = tmp.Length;
                tclass = tmp.Substring(0, tt);
            }

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<html><head><base='http://www.worlduc.com'/><title>栏目内容评价统计</title></head><body><table width='100%'>");

            Dictionary<String, UserScore> ht = new Dictionary<string, UserScore>();
            List<WorlducUtils.Comment> comments = new List<WorlducUtils.Comment>();
            List<WorlducUtils.Topic> topicList = utils.GetGroupTopicListBy(txtBlogUrl.Text);
            foreach (WorlducUtils.Topic t in topicList)
            {
                sb.AppendFormat("<tr><td colspan='5' style='width:100%;'><hr/>[{0}]{1}<hr/></td></tr>",
                           t.Id, t.Title);
                txtHint.AppendText(Environment.NewLine + t.Title);
                List<WorlducUtils.Comment> list = utils.GetCommentByTopicId(t.Id);

                list.Sort();
                int rowNo = 1;
                // 10-k/5
                sb.AppendFormat("<tr><td style='width:100px'>{0}</td><td style='width:100px'>{1}</td><td style='width:100px'>{2}</td><td style='width:150px'>{3}</td><td style='width:500px'><div style='display:none'>{4}</div></td></tr>",
                       "序号", "空间编号", "姓名", "评论时间", "评论内容");
                
                for (int k = 0; k < list.Count; k++)
                {
                    WorlducUtils.Comment c = list[k];
                    if (GetPerson(studentList, c.Author.Uid) == null) continue;
                    txtHint.AppendText(Environment.NewLine + c.Author);
                    sb.AppendFormat("<tr><td style='width:100px'>{0}</td><td style='width:100px'>{1}</td><td style='width:100px'>{2}</td><td style='width:150px'>{3}</td><td style='width:500px'><div style='display:none'>{4}</div></td></tr>",
                        rowNo++, c.Author.Uid, c.Author.Name, c.MyTime, c.Content);
                    setChecked(c.Author);
                    sb.AppendLine();
                    if (ht.ContainsKey(c.Author.Name))
                    {
                        ht[c.Author.Name].Score += (10 - k / 5);
                        ht[c.Author.Name].Count++;
                    }
                    else
                    {
                        ht.Add(c.Author.Name,new UserScore(1, 10 - k / 5));
                    }
                }

                if (list.Count > 0)
                {
                    comments.AddRange(list);
                }
            }
            
            int line = 1;
            sb.AppendFormat("<tr><td colspan='5' style='width:500px'>共{0}个主题，汇总统计结果如下：</td></tr>", topicList.Count);
            sb.AppendFormat("<tr><td style='width:100px'>{0}</td><td colspan='2' style='width:200px'>{1}</td><td style='width:100px'>{2}</td><td style='width:100px'>{3}</td></tr>",
                        "序号", "标题", "评论次数", "评论成绩");
            foreach (KeyValuePair<string, UserScore> kv in ht)
            {
                sb.AppendFormat("<tr><td style='width:100px'>{0}</td><td colspan='2' style='width:200px'>{1}</td><td style='width:100px'>{2}</td><td style='width:100px'>{3}</td></tr>",
                        line++, kv.Key, kv.Value.Count,kv.Value.Score);
            }

            string uncommenter = getUnCommenter();
            sb.AppendFormat("<tr><td colspan='5' style='width:500px'>{0}</td></tr>", uncommenter);

            sb.AppendLine("</table></body></html>");

            if (!Directory.Exists("tmp"))
            {
                Directory.CreateDirectory("tmp");
            }
            string fileName = "G" + gid+"_"+tclass + ".html";

            StreamWriter sw = new StreamWriter("tmp/" + fileName, false, Encoding.UTF8);
            sw.WriteLine(sb.ToString());
            sw.Close();

            FileInfo fi = new FileInfo("tmp/" + fileName);
            FrmViewDoc f = new FrmViewDoc(fi.FullName);
            f.ShowDialog();          
        }

        private void txtHint_DoubleClick(object sender, EventArgs e)
        {
            txtHint.Clear();
            txtHint.Text = "这里是消息区，双击清空消息";
        }

        private void setChecked(WorlducUtils.Comment c)
        {
            for (int i = 0; i < studentList.Count; i++)
            {
                if (studentList[i].Uid == c.Author.Uid)
                {
                    studentList[i].IsChecked = true;
                    studentList[i].content += "【" + c.Time + "】" + c.Content;
                }
            }
        }


        private void setChecked(WorlducUtils.Person p) {
            for (int i = 0; i < studentList.Count; i++) {
                if (studentList[i].Uid == p.Uid) {
                    studentList[i].IsChecked = true;
                }
            }
        }

        private string getUnCommenter() {
            StringBuilder sb2 = new StringBuilder();
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("<hr/><font color='red'>");
            //清空成未评论者
            int n = 0;
            for (int i = 0; i < studentList.Count; i++)
            {
                if (studentList[i].IsChecked)
                {
                    if (studentList[i].Count > 1)
                    {
                        sb2.Append(studentList[i].Name + "[" + studentList[i].Uid + "] (" + studentList[i].Count + "次)&nbsp; &nbsp;&nbsp;&nbsp;");
                    }
                    continue;
                }
                else
                {
                    n++;
                    sb.Append(studentList[i].Name + "[" + studentList[i].Uid + "] &nbsp; &nbsp;&nbsp;&nbsp;");
                }
            }
            sb.AppendLine("<br/>共"+n+"人未参与评论!<hr/>其中评论超过1次的人有：");
            sb.AppendLine(sb2.ToString());
            sb.AppendLine("</font><hr/>");
            return sb.ToString();
        }

        private void btnPrivateLetter_Click(object sender, EventArgs e)
        {
            if (studentList.Count <= 0)
            {
                MessageBox.Show("请先导入学生名单!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
            if (!utils.IsLogined())
            {
                MessageBox.Show("请先登录!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            //FrmPrivateLetter frm = new FrmPrivateLetter();
            //if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //{
                //清空成未评论者
                for (int i = 0; i < studentList.Count; i++)
                {
                    studentList[i].IsChecked = false;
                }
                btnPrivateLetter.Enabled = false;
                List<WorlducUtils.PrivateLetter> list = utils.GetPrivateLetters(DateTime.Now, DateTime.Now);              
                genShowHtmlFile(list);
                btnPrivateLetter.Enabled = true;
            //}
        }      

        private void btnCount_Click(object sender, EventArgs e)
        {         
            //http://group.worlduc.com/GroupShow/TopicList.aspx?gid=39575&tclass=12584&...
            //http://group.worlduc.com/GroupShow/Home.aspx?gid=560
            //http://group.worlduc.com/GroupShow/Topic.aspx?tid=4893247
            //http://worlduc.com/SpaceShow/Blog/List.aspx?sid=7872129&uid=134940
            //http://worlduc.com/SpaceShow/Blog/More.aspx?cid=770621&sid=7416891&uid=134940
            //http://worlduc.com/blog2012.aspx?bid=23685477
            if (studentList.Count <= 0)
            {
                MessageBox.Show("请先导入学生名单!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
            if (!utils.IsLogined())
            {
                MessageBox.Show("请先登录!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            //清空成未评论者
            for (int i = 0; i < studentList.Count; i++)
            {
                studentList[i].IsChecked = false;
            }
            btnCount.Enabled = false;
            string url = this.txtBlogUrl.Text;
            if (url.IndexOf("GroupShow/TopicList.aspx") > 0 || url.IndexOf("GroupShow/Home.aspx")>0)
            {
                TopicListCount();
            }
            else if (url.IndexOf("GroupShow/Topic.aspx") > 0)
            {
                TopicSingleCount();
            }
            else if (url.IndexOf("SpaceShow/Blog/List.aspx") > 0 || url.IndexOf("SpaceShow/Blog/More.aspx") > 0)
            {
                BatchArticleListCount();
            }
            else if (url.IndexOf("blog2012.aspx") > 0)
            {
                ArticleSingleCount();
            }

            //未评论者
            int n = 0;
            for (int i = 0; i < studentList.Count; i++)
            {
                if (studentList[i].IsChecked) n++;
            }
            lblComment.ForeColor = Color.Blue;
            lblComment.Text = "其中" + n + "人已评论," + (studentList.Count - n) + "人未评论!";
            btnCount.Enabled = true;
        }
        /// <summary>
        /// 获取评论列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        List<WorlducUtils.Comment> commentList;
        private void btnGetCommentList_Click(object sender, EventArgs e)
        {
            if (!utils.IsLogined())
            {
                MessageBox.Show("请先登录!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            int p = txtBlogUrl.Text.IndexOf("bid=");
            if (p <= 0)
            {
                MessageBox.Show("要统计的地址不合法!格式如下：\nhttp://worlduc.com/blog2012.aspx?bid=22657162", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            btnGetCommentList.Enabled = false;
            string bid = txtBlogUrl.Text.Substring(p + 4);
            int x = bid.IndexOf("&");
            if (x > 0)
            {
                bid = bid.Substring(0, x);
            }
            string content = utils.getReplyContentById(bid);
            commentList = utils.getCommentsByBlogId(bid);
            txtHint.AppendText("共获取评论["+commentList.Count + "]条！");
            btnGetCommentList.Enabled = true;
        }
        /// <summary>
        /// 回复评论
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReplyComment_Click(object sender, EventArgs e)
        {
            if (!utils.IsLogined())
            {
                MessageBox.Show("请先登录!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (commentList == null)
            {
                MessageBox.Show("请先获取评论列表!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string replyContent = txtMessage.Text;
            if (string.IsNullOrEmpty(replyContent))
            {
                replyContent = "<img src='http://www.worlduc.com/kindeditor401/plugins/emoticons/images/{1}.gif' alt='' border='0' />";
            }
            btnReplyComment.Enabled = false;
            foreach (WorlducUtils.Comment c in commentList)
            {
                if (c.IsReplyByMe) continue;
            loop:
                try
                {
                    bool success = utils.ReplyBlogCommentByCommentId(c.Bid, c.Id, replyContent);
                    txtHint.AppendText(c.Author.Name + "[" + c.Id + "] 回复[" + (success ? "成功" : "失败") + "]!\r\n");
                }
                catch (Exception ex)
                {
                    Thread.Sleep(1000);
                    goto loop;
                }
            }
            btnReplyComment.Enabled = true;
        }       

        private void btnViewUnComment_Click(object sender, EventArgs e)
        {
            if (studentList.Count <= 0) {
                MessageBox.Show("请先导入学生名单!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            txtHint.Clear();
            int n = 0;
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < studentList.Count; i++) {
                if (studentList[i].IsChecked) continue;
                n++;
                sb.Append(studentList[i].Name+"["+studentList[i].Uid+"]\t");
                txtHint.AppendText(Environment.NewLine +  studentList[i].Name + "[" + studentList[i].Uid + "]未评论" );
            }
            txtHint.AppendText(Environment.NewLine + "共有" + n + "个人未评论");
        }

        private void btnSendToUnComment_Click(object sender, EventArgs e)
        {
            if (!utils.IsLogined())
            {
                MessageBox.Show("请先登录!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (string.IsNullOrEmpty(txtMessage.Text)) {
                MessageBox.Show("请输入要留言的内容!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtMessage.Focus();
                return;
            }
            int n=0;
            btnSendToUnComment.Enabled = false;
            for (int i = 0; i < studentList.Count; i++)
            {
                if (studentList[i].IsChecked==chkUnComment.Checked) continue;
                n++;
                bool bOK = utils.IssueLeaveword(txtMessage.Text, studentList[i].Uid);
                if (bOK)
                {
                    txtHint.AppendText(Environment.NewLine + "给" + studentList[i] + "留言成功!");
                }
                else
                {
                    txtHint.AppendText(Environment.NewLine + "正在给" + studentList[i] + "留言失败！");                
                }
            }
            txtHint.AppendText(Environment.NewLine + "共给"+n+"人留言");
            btnSendToUnComment.Enabled = true;
        }
        
        private WorlducUtils.Person GetPerson(List<WorlducUtils.Person> list, string uid)
        {
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Uid == uid) return list[i];
            }
            return null;
        }
        private void btnImportStudent_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.InitialDirectory = Application.StartupPath;
            if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                return;
            string fileName = dlg.FileName;
            
            if (File.Exists(fileName))
            {
                studentList.Clear();
                //读取本地的好友信息
                StreamReader sr = new StreamReader(fileName, Encoding.UTF8);
                string line = sr.ReadLine();
                while (line != null && line.Length > 10)
                {
                    int x = line.IndexOf("|");
                    string name = line.Substring(0, x).Trim();
                    string url = line.Substring(x).Trim();
                    string uid = "";
                    x = url.IndexOf("uid=");
                    if (x > 0)
                    {
                        uid = url.Substring(x + 4);
                    }
                    WorlducUtils.Person p = GetPerson(studentList,uid);
                    if (p == null)
                    {
                        p = new WorlducUtils.Person(name, uid);
                        studentList.Add(p);
                    }
                    line = sr.ReadLine();
                }  
                sr.Close();
                lblCount.Text = "共有学生" + studentList.Count + "个";
            }
        }

        private void btnSaveGroup_Click(object sender, EventArgs e)
        {
           WorlducUtils.FriendGroup g = (WorlducUtils.FriendGroup)cbGroup.SelectedItem;
           string fileName = g.GroupId + "_" + g.GroupName + ".txt";
           StreamWriter sw = new StreamWriter(fileName);
           for (int i = 0; i < cbUser.Items.Count; i++) { 
                WorlducUtils.Person p = (WorlducUtils.Person)cbUser.Items[i];
                sw.WriteLine(p.Name + "|" + p.HomeUrl);
           }
           sw.Close();
           System.Diagnostics.Process.Start(fileName);
        }

        private void btnGenQA_Click(object sender, EventArgs e)
        {
            FrmGenXML frm = new FrmGenXML();
            frm.Show();
        }

        /// <summary>
        /// 留言统计
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnWordCount_Click(object sender, EventArgs e)
        {
            if (studentList.Count <= 0)
            {
                MessageBox.Show("请先导入学生名单!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (!utils.IsLogined())
            {
                MessageBox.Show("请先登录!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            FrmSetDate frm = new FrmSetDate();
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //清空成未评论者
                for (int i = 0; i < studentList.Count; i++)
                {
                    studentList[i].IsChecked = false;
                }
                btnWordCount.Enabled = false;
                List<WorlducUtils.LeaveWord> list = utils.GetWordList(frm.StartDate,frm.EndDate);
                genShowHtmlFile(list);
                btnWordCount.Enabled = true;
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            
            string path = Application.StartupPath + "\\data\\";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            OpenFileDialog dlg = new OpenFileDialog();
            string fileName = path +  STUDENTS_JOB_FILE;
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
                fileName = dlg.FileName;
            }
            saveExcel(fileName);
            
        }

        private void saveExcel(string fileName)
        {
            DataTable dt = null;
            string path = Application.StartupPath + "\\data\\";
            try
            {                
                dt = ExcelUtil.ImportExceltoDt(fileName);                                
            }
           
            catch { }
            fileName = path + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx";
            if (dt == null)
            {
                studentList.Sort();
                dt = new DataTable();
                dt.Columns.Add("ID");
                dt.Columns.Add("学号");
                dt.Columns.Add("编号");
                dt.Columns.Add("姓名");
                dt.Columns.Add(txtBlogUrl.Text.Trim());
                DataColumn[] keys = new DataColumn[1];
                keys[0] = dt.Columns["编号"];
                dt.PrimaryKey = keys;
                int n = dt.Columns.Count;
                for (int i = 0; i < studentList.Count; i++)
                {
                    DataRow dr = dt.NewRow();
                    dr[2] = studentList[i].Uid;
                    dr[3] = studentList[i].Name;
                    if (studentList[i].IsChecked)
                        dr[4] = "已交";
                    else
                        dr[4] = "未交";
                    dt.Rows.Add(dr);
                }
                ExcelUtil.ExportDTtoExcel(dt, "作业统计", fileName);
            }
            else
            {
                int n = dt.Columns.Count;
                int nn = dt.Rows.Count;
                DataColumn[] keys = new DataColumn[1];
                keys[0] = dt.Columns["编号"];
                dt.PrimaryKey = keys;
                int colIndex = -1;
                for (int i = 4; i < dt.Columns.Count; i++)
                {
                    if (dt.Columns[i].Caption == txtBlogUrl.Text.Trim())
                    {
                        colIndex = i;
                        break;
                    }
                }
                if (colIndex == -1)
                {
                    dt.Columns.Add(txtBlogUrl.Text.Trim());
                    colIndex = dt.Columns.Count - 1;
                    
                }

                for (int i = 0; i < studentList.Count; i++)
                {
                    DataRow dr = dt.Rows.Find(studentList[i].Uid);
                    if (studentList[i].IsChecked)
                        dr[colIndex] = "V";
                    else
                        dr[colIndex] = "X";
                }
                ExcelUtil.ExportDTtoExcel(dt, "作业统计", fileName);
            }
            MessageBox.Show(fileName, "保存成功！");
        }

        private void btnVisitUrl_Click(object sender, EventArgs e)
        {
            int n = int.Parse(txtNum.Text);
            for(int i=1;i<=n;i++)
            {
                string str = utils.HttpGet(txtBlogArticleUrl.Text);
                if (str.IndexOf("请不要点") >= 0)
                {
                    i--;
                    Thread.Sleep(2000);
                    txtHint.AppendText("重新访问" + Environment.NewLine);
                    continue;
                }
                txtHint.AppendText("访问" + i + "次" +  Environment.NewLine);
                Thread.Sleep(2000);
            }
        }

        private void btnVisitList_Click(object sender, EventArgs e)
        {
            btnVisitList.Enabled = false;
            Thread th = new Thread(visitBlogList);
            th.Start();
        }

        private void visitBlogList() {
            int n = int.Parse(txtNum.Text);
            for (int k = 1; k <= n; k++)
            {
                for (int i = 0; i < articleList.Count; i++)
                {
                    WorlducUtils.BlogArticle ba = articleList[i];
                    string str = utils.HttpGet(ba.Url);
                    if (str.IndexOf("请不要点") >= 0)
                    {
                        i--;
                        Thread.Sleep(2000);
                        txtHint.AppendText("重新访问" + Environment.NewLine);
                        continue;
                    }
                    txtHint.AppendText("第"+k+"次访问" + ba.Title + Environment.NewLine);
                    Thread.Sleep(2000);
                }
            }
            btnVisitList.Enabled = true;
        }

        private void btnCompare_Click(object sender, EventArgs e)
        {
            FrmExcelCompare frm = new FrmExcelCompare();
            frm.Show(this);
        }
    }
}
